package com.banciyuan.bcywebview.biz.detail.noveldetail;

import android.content.Intent;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.NovelApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.DetailDataHelper;
import com.banciyuan.bcywebview.base.view.tag.TagView;
import com.banciyuan.bcywebview.base.view.textview.ExpandedTextView;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.circles.smooth.CircleTagSmoothActivity;
import com.banciyuan.bcywebview.biz.detail.complex.ComplexDetailActivity;
import com.banciyuan.bcywebview.biz.pc.zone.smooth.SmoothPersonActivity;
import com.banciyuan.bcywebview.biz.post.write.WriteArticleActivity;
import com.banciyuan.bcywebview.biz.share.ShareActivity;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.constants.MyConstants;
import com.banciyuan.bcywebview.utils.file.ImageManager;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.Novel;
import de.greenrobot.daoexample.model.NovelSet;
import de.greenrobot.daoexample.model.TagDetail;

/**
 * Created by squall on 2015/9/11.
 */
public class NovelIndexActivity extends BaseActivity implements View.OnClickListener {

    public static final int GO_NOVELINDEX = 45564;
    private Novel novel = new Novel();

    private List<NovelSet> nslist = new ArrayList<>();
    private ProgressbarHelper mProgressbarHelper;
    private View mProgressbarView;
    private TextView action_title;
    private ImageView img_head;
    private ImageView img_back;
    private TextView index_title;
    private TextView index_writer;
    private TextView book_btn;
    private TextView has_book_btn;
    private TextView continue_btn;
    private TextView start_btn;
    private ExpandedTextView intro;
    private TagView label_area;
    private TextView chapter_count;
    protected String wns_id = "";
    private RequestQueue queue;
    private ImageLoader imageLoader;
    private LayoutInflater inflater;
    private ChapterAdapter mAdapter;
    private int save_index = 0;

    private ImageView back_img;
    private TextView update_tilte;
    private RelativeLayout update_line;
    private TextView update_time;
    private TextView subscribe_status;
    private TextView index_content_book;
    private TextView index_content_zan;
    private TextView index_content_word;
    private boolean book_flag = false;
    private ListView listview;
    private LinearLayout intro_area;
    private ImageView set_share;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_novel_index);
        initArgs();
        initActionbar();
        initProgressbar();
        initUi();
        initAction();
    }

    @Override
    protected void initArgs() {
        imageLoader = ImageLoader.getInstance();
        wns_id = getIntent().getStringExtra(gotoUtil.INTENT_VALUE_ONE);
        queue = VolleyQueue.getRquest(this);
        inflater = LayoutInflater.from(this);
    }

    @Override
    protected void initUi() {

        listview = (ListView) findViewById(R.id.listView);

        book_btn = (TextView) findViewById(R.id.index_book);
        start_btn = (TextView) findViewById(R.id.index_start);
        continue_btn = (TextView) findViewById(R.id.index_continue);
        has_book_btn = (TextView) findViewById(R.id.index_has_book);

        View head = inflater.inflate(R.layout.activity_novel_index_header, null);
        img_back = (ImageView) head.findViewById(R.id.img_blur);
        action_title = (TextView) head.findViewById(R.id.base_action_bar_title);
        back_img = (ImageView) head.findViewById(R.id.base_action_bar_home);
        action_title.setText(getString(R.string.series_detail));
        img_head = (ImageView) head.findViewById(R.id.index_img);
        index_title = (TextView) head.findViewById(R.id.index_title);
        index_content_book = (TextView) head.findViewById(R.id.index_content_book);
        index_content_zan = (TextView) head.findViewById(R.id.index_content_zan);
        index_content_word = (TextView) head.findViewById(R.id.index_content_word);
        index_writer = (TextView) head.findViewById(R.id.index_writer);

        intro = (ExpandedTextView) head.findViewById(R.id.index_summary);
        label_area = (TagView) head.findViewById(R.id.index_label_area);
        chapter_count = (TextView) head.findViewById(R.id.chapter_count);
        update_tilte = (TextView) head.findViewById(R.id.index_update_tilte);
        update_line = (RelativeLayout) head.findViewById(R.id.update_line);
        update_time = (TextView) head.findViewById(R.id.index_update_time);
        subscribe_status = (TextView) head.findViewById(R.id.index_status);
        intro_area = (LinearLayout) head.findViewById(R.id.intro_area);
        set_share = (ImageView) head.findViewById(R.id.set_share);

        listview.addHeaderView(head);

        View footer = new View(this);
        footer.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.MATCH_PARENT, UIUtils.dip2px(52, this)));
        listview.addFooterView(footer);
    }

    @Override
    protected void initAction() {
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                int index = i - 1;
                if (index < 0 || index >= nslist.size()) return;
                goDetail(nslist.get(index));
            }
        });

        continue_btn.setOnClickListener(this);
        start_btn.setOnClickListener(this);
        book_btn.setOnClickListener(this);
        has_book_btn.setOnClickListener(this);
        back_img.setOnClickListener(this);
        update_line.setOnClickListener(this);
        index_writer.setOnClickListener(this);
        set_share.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        String url = HttpUtils.BASE_URL + NovelApi.getSetdetail();

        List<BcyPair> pairList = new ArrayList<BcyPair>();
        pairList.add(new BcyPair(HttpUtils.WNS_ID, wns_id));
        pairList.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(NovelIndexActivity.this).getToken()));
        HashMap<String, String> map = HttpUtils.getData(pairList);

        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, NovelIndexActivity.this)) {
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        String result = jsonObject.getString(HttpUtils.UPLOAD_DATA);
                        Gson gson = new Gson();
                        novel = gson.fromJson(result, new TypeToken<Novel>() {
                        }.getType());
                        dealData();

                    } catch (Exception e) {
                        e.printStackTrace();
                        mProgressbarHelper.onFailed();
                    }
                } else {
                    mProgressbarHelper.onFailed();
                }

            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mProgressbarHelper.onFailed();
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, NovelIndexActivity.this, map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, errorProxy);
        queue.add(requestParam);
    }

    private void setMoreIcon() {
        if (StringUtil.notNullEqual(novel.getUid(), UserDataHelper.getInstance(this).getUid())) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                set_share.setImageDrawable(getResources().getDrawable(R.drawable.more_white, getTheme()));
            } else {
                set_share.setImageDrawable(getResources().getDrawable(R.drawable.more_white));
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                set_share.setImageDrawable(getResources().getDrawable(R.drawable.share_actionbar, getTheme()));
            } else {
                set_share.setImageDrawable(getResources().getDrawable(R.drawable.share_actionbar));
            }
        }
    }

    private void dealData() {
        setMoreIcon();
        imageLoader.displayImage(novel.getCover(), img_head, ImageOptions.options_noneDisplay, new SimpleImageLoadingListener() {
            @Override
            public void onLoadingComplete(String imageUri, View view, final Bitmap loadedImage) {
                new AsyncTask<Void, Bitmap, Bitmap>() {
                    @Override
                    protected Bitmap doInBackground(Void... params) {
                        Bitmap bitmap = ThumbnailUtils.extractThumbnail(loadedImage, 200, 200);
                        try {
                            return ImageManager.fastblur(bitmap, 20);
                        } catch (Exception e) {
                            return null;
                        }
                    }

                    @Override
                    protected void onPostExecute(Bitmap bitmap) {
                        if (bitmap != null) {
                            img_back.setImageBitmap(bitmap);
                        }
                    }
                }.execute();
            }
        });

        if (novel.isSet_end()) {
            subscribe_status.setText(getString(R.string.series_done));
        } else {
            subscribe_status.setText(getString(R.string.series_ing));
        }
        if (!TextUtils.isEmpty(novel.getTitle())) {
            index_title.setText(Html.fromHtml(novel.getTitle()));
        }
        index_content_book.setText(String.valueOf(novel.getSubscribe_num()));
        if (!TextUtils.isEmpty(novel.getDing_num())) {
            index_content_zan.setText(novel.getDing_num());
        }
        if (!TextUtils.isEmpty(novel.getSet_word_count())) {
            index_content_word.setText(novel.getSet_word_count());
        }
        index_writer.setText(String.format(getString(R.string.writer_container), novel.getUname()));
        String time = StringUtil.getOppositeTime(novel.getMtime());
        if (time.contains(getString(R.string.mouth_before))) {
            update_line.setVisibility(View.GONE);
        } else {
            if (!novel.getSet_posts().isEmpty()) {
                update_tilte.setText(Html.fromHtml(novel.getSet_posts().get(novel.getSet_posts().size() - 1).getTitle()));
                update_time.setText(time);
            }
        }
        if (!TextUtils.isEmpty(novel.getIntro())) {
            intro_area.setVisibility(View.VISIBLE);
            intro.setText(new SpannableString(StringUtil.htmlDecoder(novel.getIntro())), true, new ExpandedTextView.OnProcessClick() {
                @Override
                public SpannableString onProcessSucc(CharSequence text) {
                    return new SpannableString(text);
                }
            }, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    intro.setMaxLines(200);
                }
            }, R.string.open_more_no_format, 3);
        } else {
            intro_area.setVisibility(View.GONE);
        }
        if (!novel.getTags().isEmpty() || !TextUtils.isEmpty(novel.getWork())) {
            label_area.setVisibility(View.VISIBLE);
        } else {
            label_area.setVisibility(View.GONE);
        }
        List<TagDetail> tlist = new ArrayList<>();
        if (!TextUtils.isEmpty(novel.getWork())) {
            TagDetail tagDetail = new TagDetail();
            tagDetail.setWork(novel.getWork());
            tagDetail.setTag_name(novel.getWork());
            tlist.add(tagDetail);
        }
        if (!novel.getTags().isEmpty()) {
            for (String t : novel.getTags()) {
                TagDetail tagDetail = new TagDetail();
                tagDetail.setTag_name(t);
                tlist.add(tagDetail);
            }
        }
        label_area.setTlist(tlist);
        label_area.setTagViewClick(new TagView.OnTagClickListener() {
            @Override
            public void onClick(TagDetail t) {
                if (TextUtils.isEmpty(t.getWork())) {
                    Intent intent = new Intent(NovelIndexActivity.this, CircleTagSmoothActivity.class);
                    intent.putExtra("type", "tag");
                    intent.putExtra("from", 0);
                    intent.putExtra(gotoUtil.INTENT_VALUE_ONE, t.getTag_name());
                    startActivity(intent);
                }
            }
        });
        if (!StringUtil.notNullEqual(novel.getUid(), UserDataHelper.getInstance(this).getUid())) {
            if (novel.isSubscribed()) {
                book_btn.setVisibility(View.GONE);
                has_book_btn.setVisibility(View.VISIBLE);
            } else {
                book_btn.setVisibility(View.VISIBLE);
                has_book_btn.setVisibility(View.GONE);
            }
        } else {
            book_btn.setVisibility(View.VISIBLE);
            has_book_btn.setVisibility(View.GONE);
            book_btn.setText(getString(R.string.writing_series));
        }
        if (!novel.getSet_posts().isEmpty()) {
            chapter_count.setText(String.format(getString(R.string.chapter_index_container), String.valueOf(novel.getSet_posts().size())));
        } else {
            chapter_count.setText(getString(R.string.series_chapter_index));
        }
        nslist.clear();
        nslist.addAll(novel.getSet_posts());
        if (null == mAdapter) {
            mAdapter = new ChapterAdapter(nslist, NovelIndexActivity.this);
            listview.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
        readBookMark();
        mProgressbarHelper.onSuccess();

    }

    @Override
    protected void initProgressbar() {
        mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    private void readBookMark() {
        String index = SPHelper.getString(NovelIndexActivity.this, SPConstant.SPNAME_BOOKMARK, novel.getWns_id(), "0#0");
        String[] arrays = index.split("#");
        if (!arrays[0].equals("0")) {
            start_btn.setVisibility(View.GONE);
            continue_btn.setVisibility(View.VISIBLE);
            continue_btn.setText(getString(R.string.series_continue) + arrays[1] + getString(R.string.series_chapter));
            save_index = Integer.parseInt(arrays[1]);
        } else {
            start_btn.setVisibility(View.VISIBLE);
            continue_btn.setVisibility(View.GONE);
        }

    }

    private void doBook(final boolean isbook) {
        book_flag = true;
        BookNovelHelper.doBook(this, isbook, novel.getWns_id(), new BookNovelHelper.NovelBookSuccess() {
            @Override
            public void onBookSuccess() {
                book_flag = false;
                if (isbook) {
                    MyToast.show(NovelIndexActivity.this, getString(R.string.book_succ));
                    book_btn.setVisibility(View.GONE);
                    has_book_btn.setVisibility(View.VISIBLE);
                } else {
                    MyToast.show(NovelIndexActivity.this, getString(R.string.debook_succ));
                    book_btn.setVisibility(View.VISIBLE);
                    has_book_btn.setVisibility(View.GONE);
                }
            }

            @Override
            public void onBookError() {
                book_flag = false;
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.index_start:
                if (!nslist.isEmpty()) {
                    goDetail(nslist.get(0));
                } else {
                    MyToast.show(NovelIndexActivity.this, getString(R.string.series_not_start));
                }
                break;
            case R.id.index_continue:
                if (!nslist.isEmpty()) {
                    int tempLastIndex = save_index - 1;
                    tempLastIndex = tempLastIndex > nslist.size() - 1 ? nslist.size() - 1 : tempLastIndex;
                    if (tempLastIndex < 0)
                        return;
                    goDetail(nslist.get(tempLastIndex));
                } else {
                    MyToast.show(NovelIndexActivity.this, getString(R.string.series_not_start));
                }
                break;
            case R.id.index_book:
                if (!StringUtil.notNullEqual(novel.getUid(), UserDataHelper.getInstance(this).getUid())) {
                    if (!book_flag) {
                        doBook(true);
                    }
                } else {
                    Intent intent = new Intent(this, WriteArticleActivity.class);
                    intent.putExtra(gotoUtil.INTENT_VALUE_ONE, novel.getTitle());
                    intent.putExtra(gotoUtil.INTENT_VALUE_TWO, String.valueOf(novel.getCount()));
                    intent.putExtra(gotoUtil.INTENT_VALUE_THREE, novel.getType());
                    intent.putExtra(gotoUtil.INTENT_VALUE_FOUR, novel.getWork());
                    intent.putExtra(gotoUtil.INTENT_VALUE_FIVE, novel.getWns_id());
                    intent.putExtra(gotoUtil.INTENT_VALUE_SIX, novel.getMid());
                    intent.putExtra("tag_array", (Serializable) novel.getTags());
                    startActivity(intent);
                }
                break;
            case R.id.index_has_book:
                if (!book_flag) {
                    doBook(false);
                }
                break;
            case R.id.base_action_bar_home:
                finish();
                break;
            case R.id.update_line:
                if (!nslist.isEmpty()) {
                    goDetail(nslist.get(nslist.size() - 1));
                }
                break;
            case R.id.index_writer:
                gotoUtil.gotoAct(this, SmoothPersonActivity.class, novel.getUid());
                break;
            case R.id.set_share:
                goShare();
                break;
        }
    }

    private void goShare() {
        Intent intent = new Intent(NovelIndexActivity.this, ShareActivity.class);
        intent.putExtra("showblock", false);
        if (novel.getUid().equals(UserDataHelper.getInstance(this).getUid())) {
            intent.putExtra("showEdit", true);
            intent.putExtra("showDelBtn", true);
        }
        intent.putExtra("showWarnBtn", false);
        intent.putExtra("showCopyLink", true);
        intent.putExtra("showShare", true);
        HashMap<String, String> map = new HashMap<String, String>();

        String url = "http://bcy.net/novel/set/detail/" + novel.getWns_id();
        if (!TextUtils.isEmpty(novel.getType()) && novel.getType().equals("fanfic")) {
            map.put("content", String.format(getString(R.string.share_novelset_dongjin), novel.getWork(), novel.getTitle(), novel.getUname(), url));
        } else {
            map.put("content", String.format(getString(R.string.share_novelset_orgin), novel.getTitle(), novel.getUname(), url));
        }
        map.put("title", String.format(getString(R.string.share_novelset_title), novel.getTitle()));
        map.put("url", url);
        if (!StringUtil.notNullEqual(novel.getCover(), MyConstants.default_avatar)) {
            map.put("imagePath", novel.getCover());
        }
        map.put("wns_id", novel.getWns_id());
        intent.putExtra("map", map);
        startActivityForResult(intent, ComplexDetailActivity.GOSHARE);
        overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
    }

    private void goDetail(NovelSet novelSet) {
        DetailDataHelper.gotoWriterDetail(NovelIndexActivity.this, novelSet.getRp_id(), novel.getWp_id(), novel.getWns_id(), true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == ComplexDetailActivity.GOSHARE) {
            if (resultCode == ShareActivity.DELETE) {
                setResult(ShareActivity.DELETE);
                finish();
            }
        }
    }
}